using System;
using System.IO;

using BLToolkit.Data;
using BLToolkit.Data.DataProvider;
using BLToolkit.DataAccess;

using TrueCode.Core.Aspects;

namespace Server.FunctionalTests.Dal.Helpers
{
  public class TemporaryDatabase : IDisposable
  {
    private readonly FbDatabase       _fbDatabase;
    private readonly FdpDataProvider  _provider;

    public TemporaryDatabase( [NotNull] string createDBScriptPath = Constants.CreateDBScriptPath, bool embeded = false )
    {
      if( createDBScriptPath == null ) throw new ArgumentNullException( "createDBScriptPath" );
      _provider = new FdpDataProvider();
      var dataBaseFilePath = Path.GetTempFileName();
      _fbDatabase = new FbDatabase( createDBScriptPath, dataBaseFilePath, embeded );
      Console.WriteLine( "Database is deployed to " + dataBaseFilePath );
    }

    public TAccessor GetDalc< TAccessor >( ) where TAccessor : DataAccessor
    {
      return DataAccessor.CreateInstance< TAccessor >( NewDbManager() );
    }

    public DbManager NewDbManager()
    {
      return new DbManager( _provider, _fbDatabase.ConnectionString );
    }

    public void Dispose()
    {
      _fbDatabase.Dispose();
      Console.WriteLine( "Database was successfully deleted");
    }
  }
}